package Server;

import java.util.Observable;
import java.util.Observer;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.util.Duration;

public class BierdeckelController implements Observer {
	@FXML
	private Label timerLabel;

	@FXML
	private Label playerLabel;

	@FXML
	private Label blueFlipLabel;

	@FXML
	private Label redFlipLabel;

	private Timeline timeline;
	private NetworkHandler network;
	private int blueFlips = 0;
	private int redFlips = 0;

	@FXML
	public void initialize() {
		playerLabel.setText("Zeit");
		timerLabel.setText("30");

	}

	public void startTimer() {

		if (timeline != null) {
			if(timeline.getStatus().equals(timeline.getStatus().STOPPED)){
				timeline.playFromStart();
			}else{
				timeline.stop();
			}
		} else {
			playerLabel.setText("Zeit");
			timerLabel.setText("30");
			timeline = new Timeline();
			timeline.setCycleCount(Timeline.INDEFINITE);
			timeline.getKeyFrames().add(
					new KeyFrame(Duration.seconds(1),
							new EventHandler<ActionEvent>() {
								int remainingSeconds = 30;
								int remainingPlayers = 6;

								// KeyFrame event handler
								public void handle(ActionEvent event) {
									remainingSeconds--;
									// update timerLabel
									timerLabel.setText("" + remainingSeconds);
									if (remainingSeconds <= 0) {
//										timeline.stop();
										
										remainingPlayers--;
										if(remainingPlayers == 0){
											timeline.stop();
										}else{
											remainingSeconds = 30;
										}
									}
								}
							}));
			timeline.playFromStart();
		}
	}

	public void setNetwork(NetworkHandler handler) {
		network = handler;
		network.addObserver(this);
	}

	@Override
	public void update(Observable o, Object arg) {
		String message = (String) arg;
		System.out.println(message+"server");
		if (message.contains("flip")) {
			if (message.contains("blue")) {
				blueFlips++;
				Platform.runLater(new Runnable() {
					
					@Override
					public void run() {
						blueFlipLabel.setText("" + blueFlips);
						
					}
				});
			}
			if (message.contains("red")) {
				redFlips++;
				Platform.runLater(new Runnable() {
					
					@Override
					public void run() {
						redFlipLabel.setText("" + redFlips);
						
					}
				});
			}
		}
	}

	public void setFlips(String blueFlips, String redFlips) {
		blueFlipLabel.setText("" + blueFlips);
		redFlipLabel.setText("" + redFlips);
	}
}
